package com.weichai.app.page.home.viewmodel;


import static com.weichai.app.arch.config.CacheConstant.KEY_USER_INFO;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kunminx.architecture.ui.callback.UnPeekLiveData;
import com.weichai.app.R;
import com.weichai.app.arch.base.BaseViewModel;
import com.weichai.app.arch.config.CacheConstant;
import com.weichai.app.arch.http.ApiException;
import com.weichai.app.arch.http.ApiManager;
import com.weichai.app.arch.http.ApiSubscriber;
import com.weichai.app.arch.http.ApiTransformer;
import com.weichai.app.arch.utils.MMKVUtil;
import com.weichai.app.bean.AdvEntity;
import com.weichai.app.bean.BaseResult;
import com.weichai.app.bean.EntranceEntity;
import com.weichai.app.bean.InformationEntity;
import com.weichai.app.bean.MaintenanceOrderEntity;
import com.weichai.app.bean.NewsEntity;
import com.weichai.app.bean.ScanEntity;
import com.weichai.app.bean.UserInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName: HomeVM
 * @Description:
 * @Author: 祖安
 * @Date: 2021/9/1 4:49 下午
 */
public class HomeVM extends BaseViewModel {
    public UnPeekLiveData<List<InformationEntity.ListBean>> informationEntityList = new UnPeekLiveData<>();
    public UnPeekLiveData<List<EntranceEntity>> entranceList = new UnPeekLiveData<>();
    public UnPeekLiveData<List<AdvEntity>> advEntityList = new UnPeekLiveData<>();
    public UnPeekLiveData<List<NewsEntity>> newsEntityList = new UnPeekLiveData<>();
    public UnPeekLiveData<MaintenanceOrderEntity> maintenanceOrderEntity = new UnPeekLiveData<>();
    private List<EntranceEntity> list = new ArrayList<>();
    private final List<EntranceEntity> serviceList = new ArrayList<>();
    public UnPeekLiveData<Boolean> refresh = new UnPeekLiveData<>();
    public UnPeekLiveData<Boolean> loadMore = new UnPeekLiveData<>();
    public UnPeekLiveData<Boolean> loadMoreEnd = new UnPeekLiveData<>();
    public UnPeekLiveData<Integer> motorState = new UnPeekLiveData<>();
    public UnPeekLiveData<String> phoneNumber = new UnPeekLiveData<>();

    public void clickSearch() {
        navigate(R.id.search_page);
    }

    public void getList(boolean isRefresh) {
        if (isRefresh) {
            PAGE_NUM = 1;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", PAGE_NUM);
        params.put("pageSize", PAGE_SIZE);

        ApiManager.getInstance()
                .informationPage(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<InformationEntity>(false, false, this) {
                    @Override
                    public void onSuccess(BaseResult<InformationEntity> result) {
                        PAGE_NUM++;
                        if (isRefresh) {
                            refresh.setValue(true);
                        } else {
                            loadMore.setValue(true);
                        }
                        List<InformationEntity.ListBean> listBeanList = informationEntityList.getValue();
                        InformationEntity informationEntity = result.data;
                        if (null != informationEntity) {
                            if (isRefresh) {
                                informationEntityList.setValue(informationEntity.list);
                            } else {
                                if (null == listBeanList) {
                                    listBeanList = new ArrayList<>();
                                }
                                if (null != informationEntity.list && !informationEntity.list.isEmpty()) {
                                    listBeanList.addAll(informationEntity.list);
                                    informationEntityList.setValue(listBeanList);
                                }
                            }
                            if (!informationEntity.hasNextPage) {
                                loadMoreEnd.setValue(true);
                            }
                        }
                    }

                    @Override
                    public void onFail(ApiException apiException) {
                        super.onFail(apiException);
                        if (isRefresh) {
                            refresh.setValue(true);
                        } else {
                            loadMore.setValue(true);
                        }
                    }
                });
    }

    /**
     * 点赞
     */
    public void likesRecordAdd(String newsCode, int position) {
        UserInfo user = MMKVUtil.getParcelable(KEY_USER_INFO, UserInfo.class);
        if (user != null) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("newsCode", newsCode);
            params.put("userCode", user.userCode);

            ApiManager.getInstance()
                    .likesRecordAdd(params)
                    .compose(new ApiTransformer<>())
                    .subscribeWith(new ApiSubscriber<String>(true, false, this) {
                        @Override
                        public void onSuccess(BaseResult<String> result) {
                            List<InformationEntity.ListBean> listBeanList = informationEntityList.getValue();
                            if (null != listBeanList) {
                                InformationEntity.ListBean listBean = listBeanList.get(position);
                                listBean.likes++;
                                listBean.like = 1;
                                informationEntityList.setValue(listBeanList);
                            }
                        }
                    });
        }
    }

    /**
     * 取消点赞
     */
    public void likesRecordModify(String newsCode, int position) {
        UserInfo user = MMKVUtil.getParcelable(KEY_USER_INFO, UserInfo.class);
        if (user != null) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("newsCode", newsCode);
            params.put("userCode", user.userCode);

            ApiManager.getInstance()
                    .likesRecordModify(params)
                    .compose(new ApiTransformer<>())
                    .subscribeWith(new ApiSubscriber<String>(true, false, this) {
                        @Override
                        public void onSuccess(BaseResult<String> result) {
                            List<InformationEntity.ListBean> listBeanList = informationEntityList.getValue();
                            if (null != listBeanList) {
                                InformationEntity.ListBean listBean = listBeanList.get(position);
                                listBean.likes--;
                                listBean.like = 0;
                                informationEntityList.setValue(listBeanList);
                            }
                        }
                    });
        }
    }

    public void getProgressListData() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("currentTime", System.currentTimeMillis());
        params.put("engineCode", "234234");

        ApiManager.getInstance()
                .queryOrder(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<List<MaintenanceOrderEntity>>(false, false, this) {
                    @Override
                    public void onSuccess(BaseResult<List<MaintenanceOrderEntity>> result) {
                        if (null != result.data && !result.data.isEmpty()) {
                            maintenanceOrderEntity.setValue(result.data.get(0));
                        } else {
                            maintenanceOrderEntity.setValue(new MaintenanceOrderEntity());
                        }
                    }
                });
    }

    public void getEntranceList() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", PAGE_NUM);
        params.put("pageSize", PAGE_SIZE);

        ApiManager.getInstance()
                .apply(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<List<EntranceEntity>>(false, false, this) {
                    @Override
                    public void onSuccess(BaseResult<List<EntranceEntity>> result) {
                        if (null != result.data) {
                            list.clear();
                            serviceList.clear();
                            Gson gson = new Gson();
                            String entranceListJson = MMKVUtil.getString(CacheConstant.KEY_ENTRANCE_HOME);
                            if (!TextUtils.isEmpty(entranceListJson)) {
                                list = gson.fromJson(entranceListJson, new TypeToken<List<EntranceEntity>>() {
                                }.getType());
                                List<EntranceEntity> service = new ArrayList<>();
                                for (EntranceEntity entranceEntity : result.data) {
                                    if (!list.contains(entranceEntity)) {
                                        service.add(entranceEntity);
                                    }
                                }
                                serviceList.addAll(service);
                            } else {
                                if (result.data.size() > 6) {
                                    for (int i = 0; i < 6; i++) {
                                        list.add(result.data.get(i));
                                    }
                                    for (int i = 6; i < result.data.size(); i++) {
                                        serviceList.add(result.data.get(i));
                                    }
                                } else {
                                    list.addAll(result.data);
                                }
                                MMKVUtil.save(CacheConstant.KEY_ENTRANCE_HOME, gson.toJson(list));
                            }
                            MMKVUtil.save(CacheConstant.KEY_ENTRANCE_SERVICE, gson.toJson(serviceList));
                            list.add(0, new EntranceEntity(R.mipmap.ic_customer_service_phone, "客服电话"));
                            list.add(new EntranceEntity(R.mipmap.ic_more, "更多"));
                            entranceList.setValue(list);
                        }
                    }
                });
    }

    /**
     * 轮播图
     */
    public void getAdvList() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", PAGE_NUM);
        params.put("pageSize", PAGE_SIZE);

        ApiManager.getInstance()
                .carousel(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<List<AdvEntity>>(true, false, this) {
                    @Override
                    public void onSuccess(BaseResult<List<AdvEntity>> result) {
                        advEntityList.setValue(result.data);
                    }
                });
    }

    /**
     * 扫描发动机二维码查询
     */
    public void motorByState(String content) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", 1);
        params.put("webSite", content);

        ApiManager.getInstance()
                .motorByState(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<ScanEntity>(true, false, this) {
                    @Override
                    public void onSuccess(BaseResult<ScanEntity> result) {
                        if (null != result.data) {
                            List<Integer> motorStateList = result.data.motorState;
                            if (null != motorStateList && motorStateList.size() > 0) {
                                motorState.setValue(motorStateList.get(0));
                            }
                        }
                    }
                });
    }

    /**
     * 获取客服电话
     */
    public void getPhoneNumber() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("dimension", "");
        params.put("longitude", "");
        params.put("enginsCode", "");

        ApiManager.getInstance()
                .getPhoneNumber(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<String>(false, false, this) {
                    @Override
                    public void onSuccess(BaseResult<String> result) {
                        if (null != result.data) {
                            phoneNumber.setValue(result.data);
                        }
                    }
                });
    }

    /**
     * 消息
     */
    public void queryEffective() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", PAGE_NUM);
        params.put("pageSize", PAGE_SIZE);

        ApiManager.getInstance()
                .queryEffective(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<List<NewsEntity>>(false, false, this) {
                    @Override
                    public void onSuccess(BaseResult<List<NewsEntity>> result) {
                        if (null != result.data && !result.data.isEmpty()) {
                            newsEntityList.setValue(result.data);
                        }
                    }
                });
    }
}
